#include "GdfPreCompile.h"
#include "GdfDX9Device.h"

namespace Gdf
{
	GdfDX9Device::GdfDX9Device(HWND hwnd)
		:mHwnd(hwnd)
		,mDx(NULL)
		,mDxDevice(NULL)
	{
	}

	GdfDX9Device::~GdfDX9Device()
	{
		ReleaseDevice();
	}

	bool GdfDX9Device::CreateDevice()
	{
		// Create the D3D object, which is needed to create the D3DDevice.
		if( NULL == ( mDx = Direct3DCreate9( D3D_SDK_VERSION ) ) )
		{
			mDx = NULL;
			return false;
		}

		D3DPRESENT_PARAMETERS d3dpp;
		ZeroMemory( &d3dpp, sizeof( d3dpp ) );
		d3dpp.Windowed = TRUE;
		d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
		d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

 		if( FAILED(
 				mDx->CreateDevice(
 					D3DADAPTER_DEFAULT,
 					D3DDEVTYPE_HAL,
 					mHwnd,
 					D3DCREATE_SOFTWARE_VERTEXPROCESSING,
 					&d3dpp,
 					&mDxDevice ) ) )
 		{
			mDxDevice = NULL;
			return false;
 		}

		return true;
	}
	
	void GdfDX9Device::ReleaseDevice()
	{
		if(mDxDevice)
		{
			mDxDevice->Release();
			mDxDevice = NULL;
		}

		if(mDx)
		{
			mDx->Release();
			mDx = NULL;
		}
	}

	bool GdfDX9Device::PrepareRender()
	{
		if( mDxDevice )
		{
			mDxDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB( 0, 0, 0 ), 1.0f, 0 );

			if( SUCCEEDED( mDxDevice->BeginScene() ) )
			{
				return true;
			}
		}

		return false;
	}


	bool GdfDX9Device::EndRender()
	{
		if( mDxDevice )
		{
			mDxDevice->EndScene();
			mDxDevice->Present( NULL, NULL, NULL, NULL );
		}

		return true;
	}


}